import React from 'react';
import './App.css'
import { message } from 'antd';
import axios from 'axios'
class LoginRegister extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeTab: 'login'
    };
    this.registerUsername = React.createRef();
    this.registerPassword = React.createRef();
    this.loginUsername = React.createRef();
    this.loginPassword = React.createRef();
  }

  handleTabChange = (tab) => {
    this.setState({ activeTab: tab });
  };

  handleToLogin = () => {
    axios.post('http://127.0.0.1:3001/api/login',
      { username: this.loginUsername.current.value, password: this.loginPassword.current.value }
    ).then(res => {
      const statusServer = res.data.status
      if (statusServer === 200) {
        this.props.history.push('/index');
        return message.success('登录成功');
      }
      message.warning(res.data.message)
    })
  };

  // 去注册
  handleToRegister = () => {
    axios.post('http://127.0.0.1:3001/api/registry',
      { username: this.registerUsername.current.value, password: this.registerPassword.current.value }
    ).then(res => {
      const statusServer = res.data.status
      if (statusServer === 200) {
        this.handleTabChange('login')
        return message.success('注册成功');
      }
      message.warning(res.data.message)
    })
  }

  render() {
    const { activeTab } = this.state;

    return (
      <div className="login-register-container">
        <div className="tabs">
          <div
            className={`tab ${activeTab === 'login' ? 'active' : ''}`}
            onClick={() => this.handleTabChange('login')}
          >
            登录
          </div>
          <div
            className={`tab ${activeTab === 'register' ? 'active' : ''}`}
            onClick={() => this.handleTabChange('register')}
          >
            注册
          </div>
        </div>
        <div className="content">
          {activeTab === 'login' ? (
            <div className="login-form">
              <div className="login-form">
                <input type="text" placeholder="Username" ref={this.loginUsername} />
                <input type="password" placeholder="Password" ref={this.loginPassword} />
                <button onClick={() => this.handleToLogin()}>去登陆</button>
              </div>

            </div>
          ) : (
            <div className="register-form">
              <div className="login-form">
                <input type="text" placeholder="Username" ref={this.registerUsername} />
                <input type="password" placeholder="Password" ref={this.registerPassword} />
                <button onClick={() => this.handleToRegister()}>去注册</button>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default LoginRegister;
